<?php

namespace App\Http\Controllers\Site\Custom\Provider;

use App\B2BProject\AttachmentPrivateFiles;
use App\B2BProject\Custom\Business\ProviderAuthorization;
use App\B2BProject\Custom\Business\Store;
use App\B2BProject\Site\HelperControllerBuildTrait;
use App\B2BProject\Custom\MemberInformation;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Validator;
use Auth;
use Illuminate\Support\Str;

class StoreController extends Controller
{
    use HelperControllerBuildTrait;

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $store       = Auth::user()->store; // member表关联store表
        $information = Auth::user()->information;

        if ($request->ajax()) {
            return response()->json([
                'data' => [
                    'id'                    => '',
                    'company_email'         => Auth::user()->email,
                    'logo'                  => $store->store_logo,
                    'company'               => $information->company,
                    'legal'                 => $information->legal,
                    'legal_gender'          => $information->legal_gender,
                    'identification_number' => $information->identification_number,
                    'provid'                => $information->province_id,
                    'cityid'                => $information->city_id,
                    'areaid'                => $information->county_id,
                    'address'               => $information->address,
                    'contact_phone'         => $information->contact_phone,
                    'contact_email'         => $information->contact_email,
                    'categoryData'          => call_user_func_array(function (Store $store) {
                        $data = [];
                        foreach ($store->mainCategory as $category) {
                            $data[] = [
                                'id'   => $category->id,
                                'text' => $category->name,
                            ];
                        }

                        return $data;
                    }, [$store]),
                    'brandData'             => call_user_func_array(function (Store $store) {
                        $data = [];
                        foreach ($store->mainBrand as $brand) {
                            $data[] = [
                                'id'   => $brand->id,
                                'text' => $brand->name,
                            ];
                        }

                        return $data;
                    }, [$store]),
                    'email'                 => $information->contact_email,
                    'contact_person'        => $information->contact_person,
                    'lxrsex'                => 0,
                    'qq'                    => $store->contact_qq,
                    'elecFiles'             => call_user_func_array(function (Store $store, $information) {
                        $idA          = $information->legal_identity_a ? route('private.image',
                            [$information->legal_identity_a]) : '';
                        $idB          = $information->legal_identity_b ? route('private.image',
                            [$information->legal_identity_b]) : '';
                        $business     = $information->business_license ? route('private.image',
                            [$information->business_license]) : '';
                        $tax          = $store->tax_registration ? route('private.image',
                            [$store->tax_registration]) : '';
                        $organization = $store->organization_code_cert ? route('private.image',
                            [$store->organization_code_cert]) : '';

                        $return = [$idA, $idB, $business, $tax, $organization];

                        foreach ($store->authorizations as $authoriztion) {
                            $return[] = route('private.image', $authoriztion->authorization);
                        }

                        return $return;
                    }, [$store, $information]),
                ],
            ]);
        }

        return view('host/custom/provider/store/index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Requests\CompanyInformationModifyRequest $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Requests\CompanyInformationModifyRequest $request)
    {
        /**
         * @var Store $store
         */
        $store = Auth::user()->store; // member表关联store表

        /**
         * @car MemberInformation $information
         */
        $information = Auth::user()->information;

        \DB::transaction(function () use ($request, $store, $information) {
            $data = [
                'legal',
                'legal_gender',
                'legal_identity_a',
                'legal_identity_b',
                'identification_number',
                'address',
                'province_id',
                'city_id',
                'county_id',
                'contact_person',
                'contact_phone',
                'contact_email',
                'contact_qq',
                'business_license',
            ];

            $storeNeeds = [
                'tax_registration',
                'organization_code_cert',
                'authorization',
                'store_logo',
                'main_category',
                'main_brand',
                'contact_phone',
                'contact_qq',
            ];

            foreach ($storeNeeds as $name) {
                if (in_array($name, ['tax_registration', 'organization_code_cert'])) {
                    if ($request->hasFile($name) && $request->file($name)->isValid()) {
                        $attach = AttachmentPrivateFiles::findOrFail($store->$name);
                        // 无视文件存在与否直接删除
                        unlink(base_path(trim($attach->local_path, '/\/')));

                        $attach->delete();

                        $attach       = AttachmentPrivateFiles::setNewUploadFile($request->file($name), "/$name");
                        $store->$name = $attach->id;
                    }
                } elseif ($name == 'authorization') {
                    $files = $request->file($name);
                    $queue = [];
                    foreach ($files as $key => $file) {
                        if (is_null($file)) {
                            continue;
                        }

                        if ($key > 4) {
                            continue;
                        }

                        if ($file->isValid()) {
                            $queue[$key] = $file;
                        }
                    }

                    $oldAuthorizations = $store->authorizations;

                    foreach ($oldAuthorizations as $key => $authorization) {
                        if (isset($queue[$key])) {
                            $attach = AttachmentPrivateFiles::findOrFail($authorization->authorization);
                            unlink(base_path(trim($attach->local_path, '/\/')));

                            $attach->delete();
                            $attach                       = AttachmentPrivateFiles::setNewUploadFile($queue[$key],
                                '/authorization');
                            $authorization->authorization = $attach->id;
                            $authorization->save();

                            unset($queue[$key]);
                        }
                    }

                    foreach ($queue as $file) {
                        $attach                    = AttachmentPrivateFiles::setNewUploadFile($file, '/authorization');
                        $providerAuthorizationBook = new ProviderAuthorization();
                        $providerAuthorizationBook->attachment()->associate($attach);
                        $store->authorizations()->save($providerAuthorizationBook);
                    }
                } elseif ($name == 'store_logo') {
                    if (!is_null($request->file('store_logo')) && $request->file('store_logo')->isValid()) {
                        unlink(base_path(trim('public' . $store->store_logo, '/\/')));

                        // 处理店铺 LOGO
                        $logo              = $request->file('store_logo');
                        $path              = "/data/upload/stores/logo";
                        $target            = $logo->move(base_path('public' .
                                                                   $path .
                                                                   sprintf("/%s/%s/%s", date('Y', time()),
                                                                       date('m', time()),
                                                                       date('d', time()))),
                            Str::random(16) . '.' . $logo->guessClientExtension());
                        $store->store_logo = str_replace(base_path('public'), '', $target);
                    }
                } elseif ($name == 'main_brand') {
                    $store->mainBrand()->sync(empty($request->input($name)) ? [] : explode(',',
                        $request->input($name)));
                } elseif ($name == 'main_category') {
                    $store->mainCategory()->sync(empty($request->input($name)) ? [] : explode(',',
                        $request->input($name)));
                } else {
                    $store->$name = $request->input($name);
                }
            }

            foreach ($data as $name) {
                if (in_array($name, [
                    'legal_identity_a',
                    'legal_identity_b',
                    'business_license',
                ])) {
                    if ($request->hasFile($name) && $request->file($name)->isValid()) {
                        $attach = AttachmentPrivateFiles::findOrFail($information->$name);

                        unlink(base_path(trim($attach->local_path, '/\/')));

                        $attach->delete();

                        $attach             = AttachmentPrivateFiles::setNewUploadFile($request->file($name), "/$name");
                        $information->$name = $attach->id;
                    }
                } else {
                    $information->$name = $request->input($name);
                }
            }

            $store->save();
            $information->save();
        });

        return redirect()->route('account.provider.company');

    }

    /**
     * 修改密码
     *
     * @param Request $request
     *
     * @return \Response
     */
    public function password(Request $request)
    {
        if (\Hash::check($request->oldpwd, Auth::user()->password)) {
            Auth::user()->password = bcrypt($request->newpwd);
            Auth::user()->save();

            if ($request->ajax()) {
                return response()->json(['data' => ['msg' => 1]]);
            }

            return response('success');
        }

        if ($request->ajax()) {
            return response()->json(['data' => '密码错误'], 403);
        }

        return response('error', 503);
    }

    /**
     * 修改邮件箱
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function email(Request $request)
    {
        if (\Hash::check($request->pwd, Auth::user()->password)) {
            Auth::user()->email = $request->email;
            Auth::user()->save();

            if ($request->ajax()) {
                return response()->json(['data' => ['msg' => 1]]);
            }

            return response('success');
        }

        if ($request->ajax()) {
            return response()->json(['data' => '密码错误'], 403);
        }

        return response('error', 503);
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int                      $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
